package com.emptyMe.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断： 没有登陆 则返回NOLOGIN 不放行
        String token = request.getHeader("X-token");
        if (token == null || token.trim().equals("")) {
            // 没有token
            // 没有登陆
            response.setContentType("application/json;charset=utf-8");
            //{"success":false,"msg":"NOLOGIN"}
            response.getWriter().write("{\"success\":false,\"msg\":\"NOLOGIN\"}");
            System.out.println("滚粗克");
            return false;
        } else {
            // 查询令牌(token)
            String value = (String) redisTemplate.opsForValue().get(token);
//            System.out.println(value);
            if (value == null || value.trim().equals("")) {
                // 令牌（token）伪造
                // 没有登陆
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"success\":false,\"msg\":\"NOLOGIN\"}");
                return false;
            } else {
                // 刷新redis的令牌过期时间
                redisTemplate.opsForValue().set(token, value, 30, TimeUnit.MINUTES);
                // 登陆了 放行
//                System.out.println("登陆了。。。。。。");
//                System.out.println("token:"+token);
//                System.out.println("value:"+value);
                return true;
            }
        }
    }
}
